<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/26 9:38
 * Modified Time: 2019/7/26 9:38
 * Version: 2.0
 */

namespace App\Modules\Partner\Services;


use App\Exceptions\AllValidatorException;
use App\Lib\Facades\FLAuth;
use App\Lib\File\AliOSS;
use App\Lib\Utilities;
use App\Models\City;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Partner\Criterias\GetInviteStoreRecordCriteria;
use App\Modules\Partner\Criterias\GetStandardIndexCriteria;
use App\Modules\Partner\Criterias\GetUserAccountCriteria;
use App\Modules\Partner\Criterias\GetWithdrawCriteria;
use App\Modules\Partner\Repositories\UserAccountRepository;
use App\Modules\Partner\Repositories\UserInviteRepository;
use App\Modules\Partner\Repositories\UserShareRepository;
use App\Modules\Partner\Repositories\UserWithdrawRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Intervention\Image\AbstractFont;
use Intervention\Image\Facades\Image;
use Intervention\Image\ImageManagerStatic;
use OSS\Core\OssException;
use OSS\OssClient;

class PartnerService extends BaseService
{
    private $storeRepository;
    private $userAccountRepository;
    private $userStoreRepository;
    private $userInviteRepository;
    private $employeeRepository;
    private $userShareRepository;
    private $aliOSS;
    private $orderRepository;
    private $memberCardRepository;
    private $userWithdrawRepository;

    public function __construct(
        UserStoreRepository $userStoreRepository,
        UserAccountRepository $userAccountRepository,
        StoreRepository $storeRepository,
        UserWithdrawRepository $userWithdrawRepository,
        EmployeeRepository $employeeRepository,
        UserShareRepository $userShareRepository,
        AliOSS $aliOSS,
        OrderRepository $orderRepository,
        MemberCardRepository $memberCardRepository,
        UserInviteRepository $userInviteRepository)
    {
        $this->storeRepository = $storeRepository;
        $this->userAccountRepository = $userAccountRepository;
        $this->userStoreRepository = $userStoreRepository;
        $this->userWithdrawRepository = $userWithdrawRepository;
        $this->employeeRepository = $employeeRepository;
        $this->userShareRepository = $userShareRepository;
        $this->aliOSS = $aliOSS;
        $this->orderRepository = $orderRepository;
        $this->memberCardRepository = $memberCardRepository;
        $this->userInviteRepository = $userInviteRepository;
    }

    /*
     * 获取邀请新商家记录
     */
    public function getInviteStoreRecord($requestData)
    {
        $pageSize = isset($requestData['pageSize']) ? $requestData['pageSize'] : 10;

        $list = $this->userInviteRepository->pushCriteria(new GetInviteStoreRecordCriteria($requestData))
            ->paginate($pageSize, ['*']);

        $list = Utilities::dealPage($list);

        return $list;

    }

    /*
     * 提现记录
     */
    public function getWithdraw($user_id, $scene, $status, $pageSize)
    {
        $list = $this->userWithdrawRepository->pushCriteria(new GetWithdrawCriteria($user_id, $scene, $status))
            ->paginate($pageSize, ['*']);

        $list = Utilities::dealPage($list);

        return $list;
    }

    /*
     * 发起提现申请
     */
    public function applyWithdraw($requestData)
    {
        $requestData['user_id'] = FLAuth::id();;
        $requestData['apply_time'] = time();

        $this->userWithdrawRepository->create($requestData);
    }

    /*
     * 获取达标指数
     */
    public function getStandardIndex($user_id)
    {


        //获取开店时间
        $user_store = $this->userStoreRepository->findByField(['uid' => $user_id])->first()->toArray();

        $store = $this->storeRepository->find($user_store['sid'])->toArray();

        $created_time = strtotime($store['created_at']);

        $min = time() - $created_time;

        if ($min / 86400 < 1) {
            $days = ceil($min / 86400) . '天';
        } elseif ($min / 86400 >= 1 && $min / 86400 < 30) {
            $days = ceil($min / 86400) . '天';
        } elseif ($min / 86400 >= 30) {
            $days = floor($min / (86400 * 30)) . '月' . ceil(($min % (86400 * 30)) / 86400) . '天';
        } else {
            $days = '错误';
        }

        //获取累计分红
        $bonus = $this->userAccountRepository->findByField(['user_id' => $user_id])->first()->bonus_amount;

        $data = $this->userStoreRepository->pushCriteria(new GetStandardIndexCriteria($user_id))->first();
        $data['days'] = $days;

        if ($data['ranking'] <= 30) {
            $ratio = 0.003;
        } elseif ($data['ranking'] > 30 && $data['ranking'] <= 100) {
            $ratio = 0.002;
        } elseif ($data['ranking'] > 100 && $data['ranking'] <= 300) {
            $ratio = 0.001;
        } elseif ($data['ranking'] > 300 && $data['ranking'] <= 1000) {
            $ratio = 0.0005;
        } else {
            $ratio = 0.0001;
        }

        //重建返回格式
        $return_data = [
            'ranking' => $data['ranking'],
            'items' => [

                [
                    'name' => '开店时间',
                    'num' => $data['days'],
                    'target' => "6个月",
                    'is_complete' => ceil($min / 86400) >= 180 ? 1 : 0
                ],

                [
                    'name' => '线上订单',
                    'num' => $data['order_num'] . "笔",
                    'target' => "20笔",
                    'is_complete' => $data['order_num'] >= 20 ? 1 : 0
                ],
                [
                    'name' => '会员数',
                    'num' => $data['member_card_num'] . "个",
                    'target' => "50个",
                    'is_complete' => $data['member_card_num'] >= 50 ? 1 : 0
                ],
                [
                    'name' => '会员卡消费次数',
                    'num' => $data['member_card_pay'] . "次",
                    'target' => "100次",
                    'is_complete' => $data['member_card_pay'] >= 100 ? 1 : 0
                ],
            ]
        ];

        return $return_data;
    }

    /*
     * 获取达标指数头部
     */
    public function getStandardIndexHeader($user_id)
    {


        //获取开店时间
        $user_store = $this->userStoreRepository->findByField(['uid' => $user_id])->first()->toArray();

        $store = $this->storeRepository->find($user_store['sid'])->toArray();

        $adcode = substr($store['adcode'],0,4)."00";
        $city_name = City::where('code',$adcode)->first()->name;
        $created_time = strtotime($store['created_at']);
        $min = time() - $created_time;

        if ($min / 86400 < 1) {
            $days = ceil($min / 86400) . '天';
        } elseif ($min / 86400 >= 1 && $min / 86400 < 30) {
            $days = ceil($min / 86400) . '天';
        } elseif ($min / 86400 >= 30) {
            $days = floor($min / (86400 * 30)) . '月' . ceil(($min % (86400 * 30)) / 86400) . '天';
        } else {
            $days = '错误';
        }

        //获取累计分红


        if(isset($this->userAccountRepository->findByField(['user_id' => $user_id])->first()->bonus_amount)){
            $bonus = $this->userAccountRepository->findByField(['user_id' => $user_id])->first()->bonus_amount;
        }else{
            $bonus = 0 ;
        }

        $data = $this->userStoreRepository->pushCriteria(new GetStandardIndexCriteria($user_id))->first();
        $data['days'] = $days;

        if ($data['ranking'] <= 30) {
            $ratio = 0.003;
        } elseif ($data['ranking'] > 30 && $data['ranking'] <= 100) {
            $ratio = 0.002;
        } elseif ($data['ranking'] > 100 && $data['ranking'] <= 300) {
            $ratio = 0.001;
        } elseif ($data['ranking'] > 300 && $data['ranking'] <= 1000) {
            $ratio = 0.0005;
        } else {
            $ratio = 0.0001;
        }

        //重建返回格式
        $return_data = [
            'bonus' => $bonus,
            'city' => $city_name,
            'ranking' => $data['ranking'],
            'ratio' => $ratio
        ];

        return $return_data;
    }

    /*
     * 获取个人账单
     */
    public function getUserAccount()
    {
        $data = $this->userAccountRepository->pushCriteria(new GetUserAccountCriteria())->first();

        return $data;
    }

    /**
     * 判断邀请码是否存在
     * @param $invite_code
     * @return bool
     */
    public function isExistInviteCode($invite_code)
    {
        if (!$this->employeeRepository->getUserByInviteCode($invite_code)) {
            throw new AllValidatorException(['msg' => '邀请码不存在']);
        }
    }

    public function inviteImg()
    {

        $bucket = config('constant.aliOss.bucket');

        $user_id = FLAuth::id();

        $invite_code = sprintf("%06d", $user_id);
        $is_exist = $this->aliOSS->checkFileExist('invite_code/' . $invite_code . 'png');

        if ($is_exist['exist']) {
            return 'https://' . $bucket . '.oss-cn-qingdao.aliyuncs.com/invite_code/.$invite_code.png';
        }

        $img = Image::make(base_path() . '/public/phone/invite_img.png');
        $img->text($invite_code, 350, 905, function (AbstractFont $font) {
            $font->file(base_path() . '/public/phone/a.TTF');
            $font->size(66);
            $font->color('#07befa');
        });
        $img_path = public_path() . '/images/' . $invite_code . '.png';
        $img->save($img_path);


        $oss_file = $this->aliOSS->uploadByPath($img_path, 'invite_code', $invite_code, 'png', false);

        unlink($img_path);

        return $oss_file['ossName'];
    }

    /**
     * 获取分享可提现金额
     * @param $user_id
     * @return array
     */
    public function getShareWithdrawMoneyNow($user_id)
    {
        //可提现的
        $user_acconut = $this->userAccountRepository->findByField('user_id', $user_id)->first();
        if(!$user_acconut){
            throw new AllValidatorException(['msg'=>'没有找到账户记录']);
        }
        //不可提现的
        $cannot_amount = $this->userShareRepository->getCannotWithdrawAmount($user_id);

        return [
            'amount' => $user_acconut?$user_acconut->share_amount_withdraw:0,
            'cannot_amount' => $cannot_amount,
            'service_charge' => ($user_acconut?$user_acconut->share_amount_withdraw:0) * 0.06

        ];
    }

    /**
     * 获取分红可提现金额
     * @param $user_id
     * @return array
     */
    public function getBonusWithdrawMoneyNow($user_id)
    {
        //可提现的
        $user_acconut = $this->userAccountRepository->findByField('user_id', $user_id)->first();


        return [
            'amount' => $user_acconut->bonus_amount_withdraw,
            'cannot_amount' => 0,
            'service_charge' => ($user_acconut->share_amount_withdraw) * 0.06

        ];
    }

    /**
     * 获取总赚取金额
     * @param $user_id
     * @return array
     */
    public function getWithdrawMoneyAll($user_id)
    {
        $user_acconut = $this->userAccountRepository->findByField('user_id', $user_id)->first();

        return [
            'share_amount' => $user_acconut?$user_acconut->share_amount:0,
            'bonus_amount' => $user_acconut?$user_acconut->bonus_amount:0
        ];
    }
}